import { Button, Card, DatePicker, Form, Input, Select, message } from "antd";
import React, { Component } from "react";
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import { JobStatus } from "@/utils/enum";
import { boolean } from "@/utils/utils";
import { connect } from "dva";
import router from "umi/router";
import styles from "./style.less";

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

@connect(({ global, companyUserManage, loading }) => ({
  listZbCompany: companyUserManage.listZbCompany,
  industryList: global.industryList,
  industryPositionList: global.industryPositionList,
  companyDepartmentList: global.companyDepartmentList,
  submitting: loading.effects['jobManage/addZbJob'],
}))
class createUpdateJob extends Component {
  // static defaultProps = {
  //   formVals: {},
  // };
  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        ...this.props.location.state
      },
      requestParams: {
        industryId: "",
        positionId: ""
      },
      staticContact: {
        contactName: "",
        contactPhone: "",
        companyId: "",
        companyDepartmentId: "",
      }
    };
  }

  componentDidMount() {
    this.getListZbCompany();
    this.getIndustryList();
  }

  getListZbCompany = () => {
    const { flag } = this.props.match.params;
    if (!boolean(flag)) return;
    this.props.dispatch({
      type: "companyUserManage/getListZbCompany"
    });
  };

  handleSubmit = e => {
    const { dispatch, form } = this.props;
    const { requestParams, formVals, staticContact } = this.state;
    const { flag } = this.props.match.params;
    form.validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        let requestData = {
          id: formVals.id,
          companyId: staticContact.companyId,
          companyDepartmentId: staticContact.companyDepartmentId,
          ...values,
          industryId: requestParams.industryId
            ? requestParams.industryId
            : formVals.industryId,
          positionId: requestParams.positionId
            ? requestParams.positionId
            : formVals.positionId
        };
        if (boolean(flag)) {
          await dispatch({
            type: "jobManage/addZbJob",
            payload: requestData
          });
          message.success("新增成功");
          router.push("/taskManagement");
        } else {
          await dispatch({
            type: "jobManage/editZbJob",
            payload: requestData
          });
          message.success("修改成功");
          router.push("/taskManagement");
        }
      }
    });
  };

  getIndustryList = () => {
    this.props.dispatch({
      type: "global/getIndustryList"
    });
  };

  handleChangeSelect = async (state, val) => {
    const { listZbCompany } = this.props;
    const { requestParams } = this.state;
    const states = { [state]: val };
    this.setState({
      requestParams: {
        ...requestParams,
        ...states
      }
    });
    if (state == "zbCompany") {
      listZbCompany.forEach(item => {
        if (item.zbCompanyResponse.id == val) {
          this.setState({
            staticContact: {
              contactName: item.userDetailResponse.name,
              contactPhone: item.zbCompanyResponse.contactPhone,
              companyId: item.zbCompanyResponse.id,
              companyDepartmentName: '',
              companyDepartmentId: '',
            }
          });
        }
      });
      this.props.form.setFieldsValue({
        companyDepartmentName: ""
      });
      this.props.dispatch({
        type: "global/getCompanyDepartmentList",
        payload: { companyId: val }
      });
    } if (state === 'zbCompanyDepartment') {
      await this.setState(prev => ({
        staticContact: { ...prev.staticContact, companyDepartmentId: val },
      }));


    } else if (state == "industryId") {
      this.props.form.setFieldsValue({
        positionId: ""
      });
      if (val) {
        this.getIndustryPositionList({ ...states });
      }
    }
  };

  getIndustryPositionList = async industryId => {
    await this.props.dispatch({
      type: "global/getIndustryPositionList",
      payload: industryId
    });
  };

  // onSearch = (val) => {
  //   console.log('search:', val);
  // }

  render() {
    const {
      form,
      listZbCompany,
      companyDepartmentList,
      industryList,
      industryPositionList,
      submitting
    } = this.props;
    const { formVals, staticContact } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 12
        },
        md: {
          span: 10
        }
      }
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 10,
          offset: 7
        }
      }
    };
    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <FormItem label="发布公司" {...formItemLayout}>
            {form.getFieldDecorator("companyName", {
              rules: [{ required: true, message: "请输入发布公司" }],
              initialValue: formVals.companyName
            })(
              <Select
                allowClear
                showSearch
                style={{ width: "100%" }}
                placeholder="请输入发布公司"
                optionFilterProp="children"
                onChange={v => this.handleChangeSelect("zbCompany", v)}
                disabled={!boolean(this.props.match.params.flag)}
              >
                {listZbCompany.map(item => (
                  <Option
                    key={item.zbCompanyResponse.id}
                    value={item.zbCompanyResponse.id}
                  >
                    {item.zbCompanyResponse.name}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>

          <FormItem label="所属部门" {...formItemLayout}>
            {form.getFieldDecorator("companyDepartmentName", {
              initialValue: formVals.companyDepartmentName
            })(
              <Select
                allowClear
                showSearch
                style={{ width: "100%" }}
                placeholder="请输入所属部门"
                optionFilterProp="children"
                onChange={v => this.handleChangeSelect("zbCompanyDepartment", v)}
                disabled={!boolean(this.props.match.params.flag)}
              >
                {companyDepartmentList?.map((item) => (
                  <Option value={item.id}>{item.name}</Option>
                ))}
              </Select>
            )}
          </FormItem>

          {staticContact.contactName && (
            <FormItem label="企业联系人" {...formItemLayout}>
              <Input value={staticContact.contactName} disabled />
            </FormItem>
          )}

          {staticContact.contactPhone && (
            <FormItem label="联系方式" {...formItemLayout}>
              <Input value={staticContact.contactPhone} disabled />
            </FormItem>
          )}

          <FormItem label="任务简述" {...formItemLayout}>
            {form.getFieldDecorator("title", {
              rules: [{ required: true, message: "请输入任务简述" }],
              initialValue: formVals.title
            })(
              <Input allowClear placeholder="请输入任务简述" maxLength={15} />
            )}
          </FormItem>

          <FormItem label="行业" {...formItemLayout}>
            {form.getFieldDecorator("industryId", {
              rules: [{ required: true, message: "请选择行业" }],
              initialValue: formVals.industryName
            })(
              <Select
                allowClear
                style={{ width: "100%" }}
                className="marginR"
                placeholder="请选择行业"
                onChange={v => this.handleChangeSelect("industryId", v)}
              >
                {industryList.map(item => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>

          <FormItem label="项目内容" {...formItemLayout}>
            {form.getFieldDecorator("positionId", {
              rules: [{ required: true, message: "请选择项目内容" }],
              initialValue: formVals.positionName
            })(
              <Select
                allowClear
                style={{ width: "100%" }}
                placeholder="请选择项目内容"
                onChange={v => this.handleChangeSelect("positionId", v)}
              >
                {industryPositionList.map(item => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>

          <FormItem label="初步预算" {...formItemLayout}>
            {form.getFieldDecorator("budgetInfo", {
              rules: [{ required: true, message: "请输入初步预算" }],
              initialValue: formVals.budgetInfo
            })(
              <TextArea
                placeholder="请输入初步预算"
                autoSize={{ minRows: 2, maxRows: 6 }}
                maxLength={200}
              />
            )}
          </FormItem>

          <FormItem label="押金金额" {...formItemLayout}>
            {form.getFieldDecorator("depositAmount", {
              rules: [{ required: true, message: "请输入押金金额" }],
              initialValue: formVals.depositAmount || 0
            })(
              // <TextArea
              //   placeholder="请输入押金金额"
              //   autoSize={{ minRows: 2, maxRows: 6 }}
              // />
              <Input type="number" />
            )}
          </FormItem>

          {Object.keys(formVals).length > 0 && (
            <FormItem label="任务状态" {...formItemLayout}>
              {form.getFieldDecorator("jobStatus", {
                rules: [{ required: true, message: "请选择任务状态" }],
                initialValue: formVals.jobStatus
              })(
                <Select
                  allowClear
                  style={{ width: "100%" }}
                  placeholder="请选择任务状态"
                >
                  {JobStatus.map(item => (
                    <Option key={item.value} value={item.value}>
                      {item.label}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          )}

          <FormItem label="任务描述" {...formItemLayout}>
            {form.getFieldDecorator("description", {
              rules: [{ required: true, message: "请输入任务描述" }],
              initialValue: formVals.description
            })(
              <TextArea
                placeholder="请输入任务描述"
                autoSize={{ minRows: 2, maxRows: 20 }}
                maxLength={4000}
              />
            )}
          </FormItem>

          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button type="primary" onClick={this.handleSubmit} loading={submitting}>
              立即发布
            </Button>
          </FormItem>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create()(createUpdateJob);
